package org.iks.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.iks.common.constant.Constant;
import org.slf4j.MDC;
import org.slf4j.event.Level;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.UUID;

/**
 * Author kzou
 * Date 2024/5/24
 * Description: 全局请求统一拦截器
 */
@Slf4j
@Component
public class GlobalTrackFilter implements Ordered, GlobalFilter {

    private static final String RECEIVE_REQUEST_TIME = "receiveRequestTime";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uuid = UUID.randomUUID().toString();
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String ip = remoteAddress == null ? "" : remoteAddress.getAddress().getHostAddress();
        request.getRemoteAddress().getHostName();
        // 设置请求Id
        request.mutate().header(Constant.RequestId, uuid);
        MDC.put(Constant.RequestId, uuid);
        // 设置IP
        exchange.getAttributes().put(Constant.OriginalRequestIp, ip);
        // 设置开始时间
        exchange.getAttributes().put(RECEIVE_REQUEST_TIME, System.currentTimeMillis());
        // 打印日志
        String requestPath = request.getURI().getPath();
        log.info("receive a request[{}] {}, host: {}, parameter: {}",
                uuid, requestPath, ip,
                request.getQueryParams()
        );
        return chain.filter(exchange).doFinally(signalType -> {
            Long startTime = exchange.getAttribute(RECEIVE_REQUEST_TIME);
            if (startTime != null) {
                // 接口耗时
                HttpStatusCode statusCode = exchange.getResponse().getStatusCode();
                Long executeTime = System.currentTimeMillis() - startTime;
                log.atLevel(statusCode != null && !statusCode.isError() ? Level.INFO : Level.WARN).log();
                log.info("request:{} executeTime: {}ms, response status: {}",
                        exchange.getRequest().getPath(),
                        executeTime,
                        exchange.getResponse().getStatusCode()
                );
            }
            MDC.clear();
        });
    }

    @Override
    public int getOrder() {
        return -1;
    }

}
